package com.duowan.realtime.scheduled.batch.processor;

import com.duowan.datawarehouse.util.FastBeanUtil;
import org.springframework.batch.item.ItemProcessor;

import java.util.Collection;
import java.util.Map;

/**
 * @author tangsicheng
 * @version 1.0
 * @since 1.0
 * 通用的processor，可以往要处理的数据中注入一个map，这个数据可以是 List<Map>, Map, Pojo,List<Pojo> 等结构
 */
//TODO 增加动态语言,例如MVEL等
public class ValueInjectProcessor implements ItemProcessor<Object, Object> {

    private Map valuesToInject;

    @Override
    public Object process(Object item) throws Exception {
        populate(item, valuesToInject);
        return item;
    }

    private void populate(Object item, Map valuesToInject) {

        if (item instanceof Collection) {
            for (Object singleItem : (Collection) item) {
                populate(singleItem, valuesToInject);
            }
        } else if (item instanceof Map) {
            injectMap((Map) item, valuesToInject);
        } else {
            FastBeanUtil.populate(item, valuesToInject);
        }
    }

    private void injectMap(Map destMap, Map mapToInject) {
        destMap.putAll(mapToInject);
    }

    public void setValuesToInject(Map<String, Object> valuesToInject) {
        this.valuesToInject = valuesToInject;
    }
}
